﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.ObjectBuilder2;

namespace IoCNamed.UnityParamsResolver
{
    public delegate object InjectionValueDelegate(Type typeToBuild, string valueName);
    
    internal class DelegatedInjectionValueResolverPolicy : IDependencyResolverPolicy
    {
        protected readonly InjectionValueDelegate InjectionDelegate;
        protected readonly Type TypeToBuild;
        protected readonly string ValueName;

        public DelegatedInjectionValueResolverPolicy(Type typeToBuild, string valueName, InjectionValueDelegate injectionDelegate)
            : base()
        {
            InjectionDelegate = injectionDelegate;
            TypeToBuild = typeToBuild;
            ValueName = valueName;
        }

        public object Resolve(IBuilderContext context)
        {
            return InjectionDelegate(TypeToBuild, ValueName);
        }
    }

    public class DelegatedInjectionValue<TValue> : TypedInjectionValue
    {
        protected readonly InjectionValueDelegate InjectionDelegate;
        protected readonly string ValueName;

        public DelegatedInjectionValue(InjectionValueDelegate injectionDelegate)
            : base(typeof(TValue))
        {
            InjectionDelegate = injectionDelegate;
        }

        public DelegatedInjectionValue(string valueName, InjectionValueDelegate injectionDelegate)
            : this(injectionDelegate)
        {
            ValueName = valueName;
        }

        public override IDependencyResolverPolicy GetResolverPolicy(Type typeToBuild)
        {
            return new DelegatedInjectionValueResolverPolicy(typeToBuild, ValueName, InjectionDelegate);
        }
    }
}
